package com.atguigu.juc.day02.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo04TryLockTimeout {

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();

        new Thread(()->{
            lock.lock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            lock.unlock();
        }, "thread-a").start();

        new Thread(()->{

            boolean lockResult = false;

            try {
                System.out.println(Thread.currentThread().getName() + " 开始执行。");

                // 尝试获取锁并可以等待一段时间
                lockResult = lock.tryLock(5, TimeUnit.SECONDS);

                if (lockResult) {
                    System.out.println(Thread.currentThread().getName() + " 得到了锁。");
                } else {
                    System.out.println(Thread.currentThread().getName() + " 没有得到锁。");
                }

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {

                if (lockResult) {
                    lock.unlock();
                }

            }

        }, "thread-b").start();
    }

}
